'use strict';
module.exports = {
	/**
	 * 此云函数的作用是根据传进来的参数，生成一个可以从其他渠道，比如抖音/短信直接跳转进微信小程序的https短链接
	 * 如https://wxaurl.cn/DlPCeYvJL4d
	 */
	main: async (event) => {

		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			tfid,
			lbid,
			tid,
			pageId,
			bd_vid,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		const db = uniCloud.database();
		// 业务逻辑开始-----------------------------------------------------------
		/*
		http调用地址：https://static-b0f23ee3-7dd8-48fa-b2c9-b246b3f1202e.bspapp.com/a.html?tfid=xxx
		*/
		if (!tfid) {
			return "no tfid";
		}

		console.log("data=", data);

		if (lbid && tid) {
			let adds = await db.collection('jl_chudian').add({
				pt: "oppo",
				ip: originalParam.context.CLIENTIP,
				tfid: tfid,
				lbid: lbid,
				tid: tid,
				callback: tid,
				pageId: pageId,
				time: new Date().getTime(),
				time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
			})
		}

		//====根据tfid从数据库获取这个id对应的详细信息，比如小程序路径，剧集,appid等====
		let tfinfo = await db.collection('a_dy_tfurl').doc(tfid).get()
		var info = tfinfo.data[0];
		//====获取结束====

		if (!info.appid) {
			return "no appid!"
		}


		let appid = info.appid;
		let appsecret = info.appsecret;

		let path = info.path;
		let tv_id = info.tv_id;
		let series = info.series;
		let invite_code = info.agentId; //投放url的agentId作为邀请码，就是创建这个url的用户ID，具有唯一性，用于区分来自不同代理商
		let middleman_id = info.middleman_id; //机构/中间人ID

		let queryStr = "tv_id=" + tv_id + "&series=" + series + "&invite_code=" + invite_code + "&path=" +
			path + "&tfid=" + tfid + "&middleman_id=" + middleman_id;

		//参考文档：https://vkdoc.fsq.pub/client/uniCloud/plus/weixin.html#%E8%8E%B7%E5%8F%96%E5%B0%8F%E7%A8%8B%E5%BA%8Furl%E9%93%BE%E6%8E%A5
		let generateRes = await vk.openapi.weixin.urllink.generate({
			appid: appid,
			appsecret: appsecret,
			path: "pages/index/index",
			query: queryStr,
			is_expire: true,
			expire_type: 1,
			expire_interval: 30, // 有效期90天
			env_version: "release", // 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
		});

		console.log("generateRes=", generateRes.url_link);
		res.url = generateRes.url_link;

		// 业务逻辑结束-----------------------------------------------------------
		return res.url;
	}
}
